#!/bin/bash

# =================================================
# 智能排产系统前端一键部署脚本
# 本地构建 + 远程部署模式
# =================================================

# 配置变量
SERVER_HOST="117.72.45.141"
SERVER_USER="root"
SERVER_PORT="22"

APP_NAME="production-scheduling-front"
BUILD_DIR="dist"
REMOTE_WEB_DIR="/var/www/${APP_NAME}"
DEPLOY_DIR="deploy-frontend"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $(date '+%Y-%m-%d %H:%M:%S') $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查本地环境
check_local_environment() {
    log_step "1. 检查本地前端环境"

    # 检查Node.js
    if ! command -v node &> /dev/null; then
        log_error "Node.js未安装，请先安装Node.js"
        log_info "下载地址: https://nodejs.org/"
        exit 1
    fi
    log_info "✅ Node.js版本: $(node --version)"

    # 检查npm
    if ! command -v npm &> /dev/null; then
        log_error "npm未安装，请先安装npm"
        exit 1
    fi
    log_info "✅ npm版本: $(npm --version)"

    # 检查package.json
    if [ ! -f "package.json" ]; then
        log_error "package.json不存在，请在前端项目根目录执行此脚本"
        exit 1
    fi
    log_info "✅ 项目配置文件检查通过"

    log_info "本地环境检查完成"
}

# 检查服务器环境
check_server_environment() {
    log_step "2. 检查服务器环境"

    # 检查SSH连接
    log_info "测试SSH连接到服务器..."
    if ssh -o BatchMode=yes -o ConnectTimeout=5 ${SERVER_USER}@${SERVER_HOST} exit &> /dev/null; then
        log_info "✅ SSH免密登录连接成功"
    else
        log_warn "❌ SSH免密登录失败，尝试密码登录..."
        if ssh -o ConnectTimeout=10 ${SERVER_USER}@${SERVER_HOST} exit; then
            log_info "✅ SSH密码登录连接成功"
            log_warn "⚠️  建议配置SSH免密登录以获得更好的体验"
            echo ""
            read -p "是否继续部署？(y/N): " -n 1 -r
            echo ""
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                log_info "部署已取消"
                exit 0
            fi
        else
            log_error "❌ SSH连接失败，请检查网络和服务器配置"
            exit 1
        fi
    fi

    # 检查服务器必要环境
    log_info "检查服务器运行环境..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        echo '=== 检查服务器环境 ==='
        
        # 检查Nginx
        if command -v nginx &> /dev/null; then
            echo '✅ Nginx已安装: \$(nginx -v 2>&1)'
        else
            echo '❌ Nginx未安装，请先安装Nginx'
            exit 1
        fi
        
        # 检查curl
        if command -v curl &> /dev/null; then
            echo '✅ curl已安装'
        else
            echo '⚠️  curl未安装，建议安装以便测试'
        fi
        
        # 检查所需目录权限
        if sudo mkdir -p ${REMOTE_WEB_DIR} 2>/dev/null; then
            echo '✅ 目录权限检查通过'
        else
            echo '❌ 无法创建部署目录，请检查权限'
            exit 1
        fi
        
        echo '✅ 服务器环境检查完成'
    "
    
    if [ $? -eq 0 ]; then
        log_info "✅ 服务器环境检查通过"
    else
        log_error "❌ 服务器环境检查失败"
        exit 1
    fi
}

# 安装依赖
install_dependencies() {
    log_step "3. 安装本地依赖"

    if [ ! -d "node_modules" ] || [ "$1" == "--force-install" ]; then
        log_info "正在安装npm依赖..."
        if npm install; then
            log_info "✅ 依赖安装成功"
        else
            log_error "❌ 依赖安装失败"
            exit 1
        fi
    else
        log_info "✅ 依赖已安装，跳过安装步骤"
    fi
}

# 构建前端项目
build_frontend() {
    log_step "4. 本地构建前端项目"

    log_info "清理旧构建文件..."
    rm -rf $BUILD_DIR

    log_info "开始前端构建..."
    if npm run build; then
        log_info "✅ 前端构建成功"
    else
        log_error "❌ 前端构建失败，请检查代码"
        exit 1
    fi

    # 检查构建结果
    if [ ! -d "$BUILD_DIR" ]; then
        log_error "❌ 构建目录不存在: $BUILD_DIR"
        exit 1
    fi

    BUILD_SIZE=$(du -sh "$BUILD_DIR" | cut -f1)
    FILE_COUNT=$(find "$BUILD_DIR" -type f | wc -l)
    log_info "✅ 构建完成 - 文件大小: $BUILD_SIZE, 文件数量: $FILE_COUNT"
}

# 准备部署文件
prepare_deploy_files() {
    log_step "5. 准备部署文件"

    # 创建部署目录
    mkdir -p $DEPLOY_DIR

    # 复制构建文件
    cp -r $BUILD_DIR/* $DEPLOY_DIR/
    log_info "✅ 前端构建文件已准备"

    # 检查nginx配置文件
    if [ ! -f "nginx.conf" ]; then
        log_error "❌ Nginx配置文件不存在: nginx.conf"
        exit 1
    fi
    
    cp nginx.conf $DEPLOY_DIR/
    log_info "✅ Nginx配置文件已准备"

    log_info "✅ 部署文件准备完成"
}

# 备份远程前端
backup_remote_frontend() {
    log_step "6. 备份远程前端"

    log_info "检查并备份远程前端..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        if [ -d ${REMOTE_WEB_DIR} ] && [ \"\$(ls -A ${REMOTE_WEB_DIR} 2>/dev/null)\" ]; then
            BACKUP_DIR=${REMOTE_WEB_DIR}.backup.\$(date +%Y%m%d_%H%M%S)
            echo '备份现有前端到: \${BACKUP_DIR}'
            sudo mv ${REMOTE_WEB_DIR} \${BACKUP_DIR}
            echo '✅ 备份完成'
        else
            echo '✅ 远程前端目录不存在或为空，无需备份'
        fi
    "
}

# 上传文件到服务器
upload_files() {
    log_step "7. 上传前端文件到服务器"

    log_info "创建远程临时目录..."
    ssh ${SERVER_USER}@${SERVER_HOST} "sudo mkdir -p /tmp/frontend-deploy"

    log_info "上传前端文件..."
    if scp -r $DEPLOY_DIR/* ${SERVER_USER}@${SERVER_HOST}:/tmp/frontend-deploy/; then
        log_info "✅ 前端文件上传成功"
    else
        log_error "❌ 前端文件上传失败"
        exit 1
    fi

    log_info "部署文件到目标位置..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        # 创建目标目录
        sudo mkdir -p ${REMOTE_WEB_DIR}
        
        # 移动文件到目标位置
        sudo cp -r /tmp/frontend-deploy/* ${REMOTE_WEB_DIR}/
        
        # 设置文件权限
        sudo chown -R nginx:nginx ${REMOTE_WEB_DIR} 2>/dev/null || sudo chown -R www-data:www-data ${REMOTE_WEB_DIR}
        sudo chmod -R 644 ${REMOTE_WEB_DIR}
        sudo find ${REMOTE_WEB_DIR} -type d -exec chmod 755 {} \;
        
        # 验证文件部署
        if [ -f ${REMOTE_WEB_DIR}/index.html ]; then
            echo '✅ 前端文件部署成功'
        else
            echo '❌ 前端文件部署失败'
            exit 1
        fi
        
        # 清理临时文件
        sudo rm -rf /tmp/frontend-deploy
    "
    
    if [ $? -eq 0 ]; then
        log_info "✅ 文件部署完成"
    else
        log_error "❌ 文件部署失败"
        exit 1
    fi
}

# 配置Nginx
configure_nginx() {
    log_step "8. 配置Nginx反向代理"

    log_info "备份现有Nginx配置..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        if [ -f /etc/nginx/sites-available/production-scheduling ]; then
            sudo cp /etc/nginx/sites-available/production-scheduling /etc/nginx/sites-available/production-scheduling.backup.\$(date +%Y%m%d_%H%M%S)
            echo '✅ Nginx配置已备份'
        fi
    "

    log_info "上传新的Nginx配置..."
    scp nginx.conf ${SERVER_USER}@${SERVER_HOST}:/tmp/nginx-production-scheduling.conf

    log_info "应用Nginx配置..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        # 复制配置文件
        sudo cp /tmp/nginx-production-scheduling.conf /etc/nginx/sites-available/production-scheduling
        
        # 创建软链接
        sudo ln -sf /etc/nginx/sites-available/production-scheduling /etc/nginx/sites-enabled/
        
        # 测试配置
        echo '测试Nginx配置...'
        if sudo nginx -t; then
            echo '✅ Nginx配置测试通过'
            
            # 重载Nginx
            echo '重载Nginx配置...'
            if sudo systemctl reload nginx; then
                echo '✅ Nginx重载成功'
            else
                echo '⚠️  Nginx重载失败，尝试重启...'
                sudo systemctl restart nginx
                echo '✅ Nginx重启完成'
            fi
        else
            echo '❌ Nginx配置测试失败'
            exit 1
        fi
        
        # 清理临时文件
        rm -f /tmp/nginx-production-scheduling.conf
    "
    
    if [ $? -eq 0 ]; then
        log_info "✅ Nginx配置成功"
    else
        log_error "❌ Nginx配置失败"
        exit 1
    fi
}

# 验证部署
verify_deployment() {
    log_step "9. 验证部署结果"

    log_info "检查服务状态..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        echo '=== Nginx服务状态 ==='
        sudo systemctl status nginx --no-pager | head -5
        
        echo '=== 端口监听状态 ==='
        netstat -tlnp | grep 8092 || echo '⚠️  8092端口未监听'
        
        echo '=== 前端文件检查 ==='
        ls -la ${REMOTE_WEB_DIR}/ | head -5
        
        echo '=== 磁盘使用情况 ==='
        du -sh ${REMOTE_WEB_DIR}
    "

    log_info "等待服务完全启动..."
    sleep 8

    log_info "测试前端访问..."
    # 多次尝试访问测试
    SUCCESS=false
    for i in {1..3}; do
        if curl -s --connect-timeout 10 "http://${SERVER_HOST}:8092" > /dev/null; then
            log_info "✅ 前端访问测试通过 (尝试 $i/3)"
            SUCCESS=true
            break
        else
            log_warn "⚠️  前端访问测试失败，重试中... ($i/3)"
            sleep 5
        fi
    done

    if [ "$SUCCESS" = true ]; then
        log_info "✅ 前端部署验证通过"
    else
        log_warn "⚠️  前端访问测试未通过，请手动检查"
    fi

    log_info "测试API代理..."
    if curl -s --connect-timeout 10 "http://${SERVER_HOST}:8092/api/" > /dev/null 2>&1; then
        log_info "✅ API代理测试通过"
    else
        log_warn "⚠️  API代理测试失败，请确保后端服务运行在8091端口"
    fi
}

# 清理部署文件
cleanup_deploy_files() {
    log_step "10. 清理部署文件"

    log_info "清理本地部署文件..."
    if [ "$1" != "--keep-deploy" ]; then
        # 清理本地临时文件
        rm -rf $DEPLOY_DIR
        log_info "✅ 本地部署目录已清理: $DEPLOY_DIR"
    else
        log_info "✅ 保留本地部署文件: $DEPLOY_DIR"
    fi

    log_info "清理服务器临时文件..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        # 清理可能残留的临时文件
        sudo rm -rf /tmp/frontend-deploy /tmp/nginx-production-scheduling.conf
        echo '✅ 服务器临时文件已清理'
    "

    log_info "✅ 文件清理完成"
}

# 显示访问指南
show_access_guide() {
    echo ""
    echo "🎉========================================🎉"
    echo "         前端部署成功完成！"
    echo "=========================================="
    echo ""
    
    log_info "🌐 应用访问信息："
    echo ""
    echo "   📱 前端应用地址: http://${SERVER_HOST}:8092"
    echo "   🔧 API接口地址: http://${SERVER_HOST}:8092/api/"
    echo "   📊 健康检查: http://${SERVER_HOST}:8092/api/health (如果后端支持)"
    echo ""
    
    log_info "🔍 访问验证步骤："
    echo ""
    echo "   1. 浏览器打开: http://${SERVER_HOST}:8092"
    echo "   2. 检查页面是否正常加载"
    echo "   3. 测试登录功能"
    echo "   4. 验证产品工艺管理模块功能"
    echo ""
    
    log_info "🛠️  故障排查命令："
    echo ""
    echo "   # 检查Nginx状态"
    echo "   ssh ${SERVER_USER}@${SERVER_HOST} 'sudo systemctl status nginx'"
    echo ""
    echo "   # 查看Nginx日志"
    echo "   ssh ${SERVER_USER}@${SERVER_HOST} 'sudo tail -f /var/log/nginx/error.log'"
    echo ""
    echo "   # 检查前端文件"
    echo "   ssh ${SERVER_USER}@${SERVER_HOST} 'ls -la ${REMOTE_WEB_DIR}/'"
    echo ""
    
    log_info "📝 重要提醒："
    echo ""
    echo "   ✅ 前端已部署到: ${REMOTE_WEB_DIR}"
    echo "   ✅ Nginx配置: /etc/nginx/sites-available/production-scheduling"
    echo "   ✅ 前端端口: 8092"
    echo "   ✅ API代理: /api/ → 后端8091端口"
    echo ""
    echo "🎯 下一步操作："
    echo ""
    echo "   1. 确保后端服务运行在8091端口"
    echo "   2. 访问前端应用测试功能"
    echo "   3. 检查API调用是否正常"
    echo ""
    echo "🎉========================================🎉"
}

# 显示帮助信息
show_help() {
    echo "智能排产系统前端部署脚本 (本地构建模式)"
    echo ""
    echo "使用方法:"
    echo "  $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --help              显示帮助信息"
    echo "  --keep-deploy       保留本地部署文件"
    echo "  --skip-build        跳过构建步骤(使用已有dist)"
    echo "  --force-install     强制重新安装依赖"
    echo "  --only-upload       仅上传文件，不重载Nginx"
    echo "  --troubleshoot      故障排查模式，收集服务器信息"
    echo "  --check-server      检查服务器环境和状态"
    echo ""
    echo "示例:"
    echo "  $0                  完整部署"
    echo "  $0 --keep-deploy    部署后保留文件"
    echo "  $0 --skip-build     跳过构建直接部署"
    echo "  $0 --troubleshoot   排查部署问题"
    echo ""
    echo "环境要求:"
    echo "  本地: Node.js + npm"
    echo "  服务器: Nginx + SSH访问权限"
}

# 故障排查
troubleshoot() {
    log_step "故障排查模式"

    log_info "收集本地环境信息..."
    echo "=== 本地环境 ==="
    node --version 2>/dev/null || echo "Node.js未安装"
    npm --version 2>/dev/null || echo "npm未安装"
    [ -f package.json ] && echo "✅ package.json存在" || echo "❌ package.json不存在"
    [ -d dist ] && echo "✅ dist目录存在" || echo "❌ dist目录不存在"
    
    log_info "收集服务器信息..."
    ssh ${SERVER_USER}@${SERVER_HOST} "
        echo '=== 服务器环境 ==='
        date
        uptime
        df -h /var/www/ 2>/dev/null || echo '/var/www目录不存在'
        
        echo '=== 前端部署状态 ==='
        ls -la ${REMOTE_WEB_DIR}/ 2>/dev/null || echo '前端目录不存在'
        
        echo '=== Nginx状态 ==='
        systemctl status nginx --no-pager | head -10
        
        echo '=== Nginx配置测试 ==='
        nginx -t 2>&1 || echo 'Nginx配置测试失败'
        
        echo '=== 端口监听 ==='
        netstat -tlnp | grep -E '(8091|8092)' || echo '目标端口未监听'
        
        echo '=== 进程检查 ==='
        ps aux | grep nginx | grep -v grep || echo 'Nginx进程未运行'
        
        echo '=== 最近错误日志 ==='
        tail -5 /var/log/nginx/error.log 2>/dev/null || echo '无法读取Nginx错误日志'
    "
}

# 检查服务器状态
check_server() {
    log_step "检查服务器环境和状态"

    ssh ${SERVER_USER}@${SERVER_HOST} "
        echo '=== 服务器基本信息 ==='
        uname -a
        whoami
        
        echo '=== Nginx版本和状态 ==='
        nginx -v 2>&1
        systemctl is-active nginx
        
        echo '=== 网络监听 ==='
        netstat -tlnp | grep nginx || echo 'Nginx未监听任何端口'
        
        echo '=== 磁盘空间 ==='
        df -h /var/www/ /tmp/
        
        echo '=== 目录权限 ==='
        ls -la /var/www/ | head -10
        
        echo '=== 防火墙状态 ==='
        if command -v ufw &> /dev/null; then
            ufw status | head -10
        elif command -v firewall-cmd &> /dev/null; then
            firewall-cmd --list-ports 2>/dev/null | head -5
        else
            echo '未检测到常见防火墙工具'
        fi
    "
}

# 主函数
main() {
    local SKIP_BUILD=false
    local FORCE_INSTALL=false
    local ONLY_UPLOAD=false
    local KEEP_DEPLOY=false

    # 解析参数
    for arg in "$@"; do
        case $arg in
            --help)
                show_help
                exit 0
                ;;
            --skip-build)
                SKIP_BUILD=true
                ;;
            --force-install)
                FORCE_INSTALL=true
                ;;
            --only-upload)
                ONLY_UPLOAD=true
                ;;
            --keep-deploy)
                KEEP_DEPLOY=true
                ;;
            --troubleshoot)
                troubleshoot
                exit 0
                ;;
            --check-server)
                check_server
                exit 0
                ;;
            *)
                log_error "未知参数: $arg"
                show_help
                exit 1
                ;;
        esac
    done

    echo "🚀 智能排产系统前端部署开始 (本地构建模式)"
    echo "=================================================="

    # 执行部署流程
    check_local_environment
    check_server_environment

    if [ "$FORCE_INSTALL" = true ]; then
        install_dependencies --force-install
    else
        install_dependencies
    fi

    if [ "$SKIP_BUILD" = false ]; then
        build_frontend
    else
        log_info "跳过构建步骤"
        if [ ! -d "$BUILD_DIR" ]; then
            log_error "构建目录不存在: $BUILD_DIR，请先构建项目"
            exit 1
        fi
    fi

    prepare_deploy_files

    if [ "$ONLY_UPLOAD" = false ]; then
        backup_remote_frontend
    fi

    upload_files

    if [ "$ONLY_UPLOAD" = false ]; then
        configure_nginx
        verify_deployment
    else
        log_info "仅上传模式，跳过Nginx配置"
    fi

    if [ "$KEEP_DEPLOY" = true ]; then
        cleanup_deploy_files --keep-deploy
    else
        cleanup_deploy_files
    fi

    # 显示访问指南
    show_access_guide

    echo "=================================================="
    echo "🎉 前端部署脚本执行完成！"
}

# 执行主函数
main "$@" 